import React, { useState, useRef, useEffect } from 'react'
import { X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'

interface TagInputProps {
  // 默认标签列表
  defaultTags?: string[]
  // 最大标签数量
  maxTags?: number
  // 是否允许重复标签
  allowDuplicates?: boolean
  // 标签变化时的回调函数
  onChange?: (tags: string[]) => void
  // 添加标签时的验证函数
  validator?: (tag: string) => boolean
  // 输入框的占位符
  placeholder?: string
  // 是否禁用
  disabled?: boolean
}

const TagInput: React.FC<TagInputProps> = ({
  defaultTags = [],
  maxTags,
  allowDuplicates = false,
  onChange,
  validator,
  placeholder = '请输入',
  disabled = false,
}) => {
  const [tags, setTags] = useState<string[]>(defaultTags)
  const [isAdding, setIsAdding] = useState(false)
  const [inputValue, setInputValue] = useState('')
  const [error, setError] = useState<string | null>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (isAdding && inputRef.current) {
      inputRef.current.focus()
    }
  }, [isAdding])

  // 当标签改变时触发外部回调
  useEffect(() => {
    onChange?.(tags)
  }, [tags, onChange])

  const validateTag = (tag: string): boolean => {
    // 清除之前的错误
    setError(null)

    // 空值检查
    if (!tag.trim()) {
      setError('标签不能为空')
      return false
    }

    // 重复检查
    if (!allowDuplicates && tags.includes(tag)) {
      setError('标签已存在')
      return false
    }

    // 数量限制检查
    if (maxTags && tags.length >= maxTags) {
      setError(`标签数量不能超过 ${maxTags} 个`)
      return false
    }

    // 自定义验证
    if (validator && !validator(tag)) {
      setError('标签不符合要求')
      return false
    }

    return true
  }

  const handleAddTag = () => {
    const newTag = inputValue.trim()

    if (validateTag(newTag)) {
      setTags([...tags, newTag])
      setInputValue('')
      setIsAdding(false)
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      handleAddTag()
    }
    // 支持使用退格键删除最后一个标签
    if (e.key === 'Backspace' && !inputValue) {
      e.preventDefault()
      handleDelete(tags.length - 1)
    }
  }

  const handleBlur = () => {
    handleAddTag()
  }

  const handleDelete = (indexToDelete: number) => {
    setTags(tags.filter((_, index) => index !== indexToDelete))
  }

  return (
    <div className="space-y-1">
      <div className="flex flex-wrap gap-2 p-2 border rounded-md min-h-12 items-center">
        {tags.map((tag, index) => (
          <div
            key={index}
            className="flex items-center gap-1 px-2 py-1 bg-gray-100 rounded-md"
          >
            <span className="text-sm">{tag}</span>
            {!disabled && (
              <button
                onClick={() => handleDelete(index)}
                className="text-gray-500 hover:text-gray-700"
              >
                <X size={14} />
              </button>
            )}
          </div>
        ))}

        {!disabled &&
          (maxTags ? tags.length < maxTags : true) &&
          (isAdding ? (
            <Input
              ref={inputRef}
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyDown}
              onBlur={handleBlur}
              placeholder={placeholder}
              className="w-24 h-8"
            />
          ) : (
            <Button
              variant="ghost"
              size="sm"
              className="h-8 text-gray-500"
              onClick={() => setIsAdding(true)}
            >
              + 添加
            </Button>
          ))}
      </div>
      {error && <p className="text-sm text-red-500">{error}</p>}
    </div>
  )
}

export default TagInput
